package com.qingcheng.service.impl;

import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.CartService;
import com.qingcheng.service.CategoryFegin;
import com.qingcheng.service.PreferentialService;
import com.qingcheng.service.SkuFegin;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuFegin skuFegin;

    @Autowired
    private CategoryFegin categoryFegin;

    @Autowired
    private PreferentialService preferentialService;

    @Override
    public List<Map<String, Object>> findCartList(String username) {
        //从缓冲中提取购物车
        List<Map<String,Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if(cartList == null){
            cartList = new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public void addItem(String username, String skuId, Integer num) {
        List<Map<String, Object>> cartList = findCartList(username);

        boolean flag = false; //搜否存在购物车
        for (Map<String, Object> map : cartList) {
            OrderItem item = (OrderItem) map.get("item");
            if(item.getSkuId().equals(skuId)){ //判断购物车是否存在该商品
                if(item.getWeight() <= 0){ //重量为0,删除该商品
                    cartList.remove(map);
                    flag = true;
                    break;
                }

                int weight = item.getWeight()/item.getNum(); //单个商品重量
                item.setNum(item.getNum()+num);//数量变更
                item.setMoney(item.getPrice()*item.getNum());//金额变更
                item.setWeight(weight*item.getNum());

                if(item.getWeight() <= 0){ //重量为0,删除该商品
                    cartList.remove(map);
                }
                flag = true;
                break;
            }
        }
        if(flag == false){
            Sku sku = skuFegin.findById(skuId);
            if(sku == null){
                throw new RuntimeException("商品不存在");
            }
            if(!"1".equals(sku.getStatus())){
                throw new RuntimeException("商品状态不合法");
            }
            if(sku.getNum()<0){
                throw new RuntimeException("商品数量不足");
            }

            //创建订单详情
            OrderItem orderItem = new OrderItem();
            orderItem.setCategoryId3(sku.getCategoryId()); //三级分类id
            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());

            orderItem.setMoney(orderItem.getPrice()*num);
            if(orderItem.getWeight() == null){
                orderItem.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight()*num);

            //分类缓存二级
            Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if(category3 == null){
                category3 = categoryFegin.findById(sku.getCategoryId()); //根据三级分类id查2级
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(),category3);
            }
            orderItem.setCategoryId2(category3.getParentId());
            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());

            if(category2 == null){
                category2 = categoryFegin.findById(category3.getParentId()); //根据二级分类id查1级
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getParentId(),category2);
            }
            orderItem.setCategoryId1(category2.getParentId());

            //创建页面所要的数据
            Map<String,Object> map = new HashMap<>();
            map.put("item", orderItem);
            map.put("checked",true);

            cartList.add(map);
        }

        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);

    }

    @Override
    public void deleteCart(String username) {
        //获得选中购物车
        List<Map<String, Object>> cartList = findCartList(username).stream().filter(cart -> (boolean) cart.get("checked")==false)
                .collect(Collectors.toList());

        //将原来的覆盖
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        List<Map<String, Object>> cartList = findCartList(username);
        boolean isOk =false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem =  (OrderItem)map.get("item");
            if(skuId.equals(orderItem.getSkuId())){
                map.put("checked",checked);
                isOk =true;
                break;
            }
        }
        if(isOk){
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        }
        return isOk;
    }

    @Override
    public int preferential(String username) {
        //获取选中的购物车
        List<OrderItem> orderItems = findCartList(username).stream()
                .filter(cart -> (boolean) cart.get("checked") == true)
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //按分类聚合统计每个分类的金额
        // 1  200
        // 2  500
        Map<Integer, IntSummaryStatistics> cartMap = orderItems.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3, Collectors.summarizingInt(OrderItem::getMoney)));

        int allPreMoney = 0; //累计优惠金额
        for (Integer categoryId: cartMap.keySet()){
            int money = (int) cartMap.get(categoryId).getSum();
            int preMoney = preferentialService.findPreMoneyByCategoryId(categoryId,money);//计算优惠金额
            allPreMoney += preMoney;
        }

        return allPreMoney;
    }

    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
        //获取购物车
        List<Map<String, Object>> cartList = findCartList(username);

        //循环购物车刷新
        for(Map<String, Object> cart:cartList){
            OrderItem orderItem = (OrderItem) cart.get("item");
            Sku sku = skuFegin.findById(orderItem.getSkuId()); //得到最新商品信息
            orderItem.setPrice(sku.getPrice()); //设置最新商品信息
            orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());
        }

        //保存购物车
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);

        return cartList;
    }
}
